<template>
    <div :class="{'hidden':hidden}" class="pagination-container">
        <el-pagination
                :background="background"
                :current-page.sync="currentPage"
                :page-size.sync="pageSize"
                :layout="layout"
                :page-sizes="pageSizes"
                :pager-count="pagerCount"
                :total="total"
                v-bind="$attrs"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup>
import {toRefs, computed} from "vue";

const emit = defineEmits('update:page', 'update:limit', 'pagination')
const props = defineProps({
    //总条目数
    total: {
        required: true,
        type: Number
    },
    //页数
    page: {
        type: Number,
        default: 1
    },
    //条数
    limit: {
        type: Number,
        default: 10
    },
    //选择器选项
    pageSizes: {
        type: Array,
        default() {
            return [10, 20, 30, 50]
        }
    },
    //最大页码按钮数
    pagerCount: {
        type: Number,
        default: 7
    },
    //组件布局
    layout: {
        type: String,
        default: 'total, sizes, prev, pager, next, jumper'
    },
    //是否为分页按钮添加背景色
    background: {
        type: Boolean,
        default: true
    },
    hidden: {
        type: Boolean,
        default: false
    }
})

const {total, page, limit, pageSizes, pagerCount, layout, background, hidden} = toRefs(props)

//当前页号
const currentPage = computed({
    get() {
        return page.value
    },
    set(val) {
        emit('update:page', val)
    }
})

//当前页数
const pageSize = computed({
    get() {
        return limit.value
    },
    set(val) {
        emit('update:limit', val)
    }
})

//分页方法
function handleSizeChange(val) {
    if (currentPage.value * val > total.value) {
        currentPage.value = 1
    }
    emit('pagination', { page: currentPage.value, limit: val })
}

//分页方法
function handleCurrentChange(val) {
    emit('pagination', { page: val, limit: pageSize.value })
}

</script>

<style scoped>
.pagination-container {
    background: #fff;
}
.pagination-container.hidden {
    display: none;
}
</style>